# 蛇类
# 点以25为单位
from constant import SCREEN_X, SCREEN_Y, BOARD_SIZE, PLAYER_INIT_LOC


class SnakePlayer:
    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    def __init__(self, pygame):
        self.dirction = pygame.K_UP
        self.body = []
        self.pygame = pygame
        for x in range(10):
            self.addnode()

    # 无论何时 都在前端增加蛇块
    def addnode(self):
        left, top = PLAYER_INIT_LOC
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = self.pygame.Rect(left, top, BOARD_SIZE, BOARD_SIZE)
        if self.dirction == self.pygame.K_LEFT:
            node.left -= BOARD_SIZE
        elif self.dirction == self.pygame.K_RIGHT:
            node.left += BOARD_SIZE
        elif self.dirction == self.pygame.K_UP:
            node.top -= BOARD_SIZE
        elif self.dirction == self.pygame.K_DOWN:
            node.top += BOARD_SIZE
        self.body.insert(0, node)

    # 删除最后一个块
    def delnode(self):
        self.body.pop()

    # 死亡判断
    def isdead(self):
        # 撞墙
        if self.body[0].x not in range(SCREEN_X):
            return True
        if self.body[0].y not in range(SCREEN_Y):
            return True
        if len(self.body) < 4:
            return True
        return False

    # 移动！
    def move(self):
        self.addnode()
        self.delnode()

    # 改变方向 但是左右、上下不能被逆向改变
    def changedirection(self, curkey):
        LR = [self.pygame.K_LEFT, self.pygame.K_RIGHT]
        UD = [self.pygame.K_UP, self.pygame.K_DOWN]
        if curkey in LR + UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey
